<?php

namespace App\Http\Controllers\API;

use App\Models\InnerCar;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;

class InnerParkCountController extends AppBaseController
{

    public function query(Request $request)
    {
        $this->validate($request,['date'=>'required']);

        $model = InnerCar::where('hour',$request->date);

        $parks = $this->getUserParks();
        $parkCode = $this->getParkCodes($parks);

        //车场查询条件
        if($request->get('park_code')) {
            $model = $model->whereIn('park_code',$request->park_code);
        }else{
            $model = $model->whereIn('park_code',$parkCode);
        }

        $res = $model->select(['park_code','inner_park'])->get();

        $total = 0;

        $data=$res->map(function ($item) use ($parks,$total){
            $item->name=$parks->has($item->park_code) ? $parks[$item->park_code] : '';
            return $item;
        });

        //根据传的park_code排序
        $newRes=collect([]);
        foreach ($request->park_code as $v){
            $item = $data->where('park_code',$v);
            if($item->count() > 0){
                $newRes->push($item->first());
            }
        }


        //计算合计
        $total=$newRes->sum('inner_park');
        $data=$newRes->toArray();

        array_unshift($data,['name'=>'合计','inner_park'=>$total]);

        return $this->sendResponse($data,'请求成功');
    }
}
